package cn.itcast.crm.service.impl;

import java.util.List;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import cn.itcast.crm.dao.CustomerRepository;
import cn.itcast.crm.domain.Customer;
import cn.itcast.crm.service.CustomerService;

@Service
@Transactional
public class CustomerServiceImpl implements CustomerService {

	//注入DAO
	@Autowired
	private CustomerRepository customerRepository;
	
	@Override
	public List<Customer> findNoAssociationCustomers() {
		return customerRepository.findByFixedAreaIdIsNull();
	}

	@Override
	public List<Customer> findHasAssociationFixedAreaCustomers(String fixedAreaId) {
		return customerRepository.findByFixedAreaId(fixedAreaId);
	}

	@Override
	public void associationCustomerToFixedArea(String customerIdStr, String fixedAreaId) {
		
		//接触关联
		customerRepository.clearFixedAreaId(fixedAreaId);
		
		//将接收到的id字符串切割为一个个id(切割钱需判断传过来的值是否为空)
		if(StringUtils.isBlank(customerIdStr)){
			//如果为空，则返回，不继续往下执行
		}
		
		//先将字符串按分隔符切分为id字符串数组
		String[] customerIdArray = customerIdStr.split(",");
		
		//遍历id字符串数组，获取每一个id
		for (String idStr : customerIdArray) {
			Integer id = Integer.parseInt(idStr);
			
			//调用dao完成修改操作
			customerRepository.updateFixedAreaId(fixedAreaId,id);
		}
	}

	//保存注册用户信息
	@Override
	public void regist(Customer customer) {
		customerRepository.save(customer);
	}

	//根据手机号查询客户
	@Override
	public Customer findByTelephone(String telephone) {
		return customerRepository.findByTelephone(telephone);
	}

	//根据手机号修改客户邮箱状态
	@Override
	public void updateType(String telephone) {
		customerRepository.updateType(telephone);
	}

	//用户登录
	@Override
	public Customer login(String telephone, String password) {
		return customerRepository.findByTelephoneAndPassword(telephone,password);
	}

	//根据客户地址查询定区编号
	@Override
	public String findFixedAreaIdByAddress(String address) {
		return customerRepository.findFixedAreaIdByAddress(address);
	}
}
